<template>
    <div class="p-6 bg-gray-50 min-h-screen">
        <el-card class="!border-none rounded-lg shadow-sm mb-4" shadow="never">
            <el-page-header content="种植主体详情" @back="$router.back()" class="text-lg font-medium text-gray-800" />
        </el-card>
        <el-card class="mt-4 !border-none rounded-lg shadow-sm p-6 bg-white" header="基本信息" shadow="never">
            <el-form ref="formRef" class="ls-form grid grid-cols-2 gap-6 md:gap-8" :model="formData"
                label-width="140px">
                <!-- 提交人手机号 -->
                <el-form-item label="提交人手机号：">
                    <span class="text-gray-700">{{ formData.user_account || '-' }}</span>
                </el-form-item>

                <!-- 主体名称 -->
                <el-form-item label="主体名称：">
                    <span class="text-gray-700">{{ formData.entity_name || '-' }}</span>
                </el-form-item>

                <!-- 统一社会信用代码 -->
                <el-form-item label="统一社会信用代码：">
                    <span class="text-gray-700">{{ formData.credit_code || '-' }}</span>
                </el-form-item>

                <!-- 成立日期 -->
                <el-form-item label="成立日期：">
                    <span class="text-gray-700">{{ formData.start_date || '-' }}</span>
                </el-form-item>

                <!-- 法定代表人姓名 -->
                <el-form-item label="法定代表人姓名：">
                    <span class="text-gray-700">{{ formData.oper_name || '-' }}</span>
                </el-form-item>

                <!-- 状态 -->
                <el-form-item label="状态：">
                    <span class="text-gray-700">{{ formData.status || '-' }}</span>
                </el-form-item>

                <!-- 注册号 -->
                <el-form-item label="注册号：">
                    <span class="text-gray-700">{{ formData.no || '-' }}</span>
                </el-form-item>

                <!-- 注册地址 -->
                <el-form-item label="地址：">
                    <span class="text-gray-700">{{ formData.comp_address || '-' }}</span>
                </el-form-item>

                <!-- 身份证号 -->
                <el-form-item label="身份证号：">
                    <span class="text-gray-700">{{ formData.id_card || '-' }}</span>
                </el-form-item>

                <!-- 所在地区 -->
                <el-form-item label="所在地区：">
                    <span class="text-gray-700">{{ formData.address || '-' }}</span>
                </el-form-item>

                <!-- 详细地址 -->
                <el-form-item label="详细地址：">
                    <span class="text-gray-700">{{ formData.address_detail || '-' }}</span>
                </el-form-item>

                <!-- 种植地名称 -->
                <el-form-item label="种植地名称：">
                    <span class="text-gray-700">{{ formData.field_name || '-' }}</span>
                </el-form-item>

                <!-- 位置 -->
                <el-form-item label="位置：">
                    <span class="text-gray-700">{{ formData.location || '-' }}</span>
                </el-form-item>

                <!-- 品种来源 -->
                <el-form-item label="品种来源：">
                    <span class="text-gray-700">{{ formData.variety_source || '-' }}</span>
                </el-form-item>

                <!-- 种植面积 -->
                <el-form-item label="种植面积：">
                    <span class="text-gray-700">{{ formData.planting_area || '-' }}</span>
                </el-form-item>

                <!-- 种植时间 -->
                <el-form-item label="种植时间：">
                    <span class="text-gray-700">{{ formData.planting_date || '-' }}</span>
                </el-form-item>

                <!-- 预计作货时间 -->
                <el-form-item label="预计作货时间：">
                    <span class="text-gray-700">{{ formData.estimated_harvest_date || '-' }}</span>
                </el-form-item>

                <!-- 预计作货量 -->
                <el-form-item label="预计作货量：">
                    <span class="text-gray-700">{{ formData.estimated_yield || '-' }}</span>
                </el-form-item>

                <!-- 累计采收次数 -->
                <el-form-item label="累计采收次数：">
                    <span class="text-gray-700">{{ formData.total_harvest_times || '-' }}</span>
                </el-form-item>

                <!-- 累计作货量 -->
                <el-form-item label="累计作货量：">
                    <span class="text-gray-700">{{ formData.total_yield || '-' }}</span>
                </el-form-item>

                <!-- 预计剩余作货量 -->
                <el-form-item label="预计剩余作货量：">
                    <span class="text-gray-700">{{ formData.remaining_yield || '-' }}</span>
                </el-form-item>

                <!-- 流转情况 -->
                <el-form-item label="流转情况：">
                    <span class="text-gray-700">{{ formData.circulation_info || '-' }}</span>
                </el-form-item>

                <!-- 承包情况 -->
                <el-form-item label="承包情况：">
                    <span class="text-gray-700">{{ formData.contract_info || '-' }}</span>
                </el-form-item>

                <!-- 权属情况 -->
                <el-form-item label="权属情况：">
                    <span class="text-gray-700">{{ formData.ownership_info || '-' }}</span>
                </el-form-item>

                <!-- 检测报告图片 -->
                <el-form-item label="检测报告图片：">
                    <div v-if="formData.report_images" class="flex flex-wrap items-center">
                        <el-image
                            v-for="(image, index) in Array.isArray(formData.report_images) ? formData.report_images : formData.report_images.split(',')"
                            :key="index" :src="getImageUrl(image)" fit="cover"
                            class="w-16 h-16 rounded-md object-cover mr-3 cursor-pointer hover:opacity-80 transition-opacity"
                            @click="openImageGallery(getImageArray(formData.report_images), index)" />
                    </div>
                    <span v-else class="text-red-500">无图片</span>
                </el-form-item>

                <!-- 种植环境照片 -->
                <el-form-item label="种植环境照片：">
                    <div v-if="formData.environment_images" class="flex flex-wrap items-center">
                        <!-- 检查是否为数组，若不是则按逗号分割 -->
                        <el-image
                            v-for="(image, index) in Array.isArray(formData.environment_images) ? formData.environment_images : formData.environment_images.split(',')"
                            :key="index" :src="getImageUrl(image)" fit="cover"
                            class="w-16 h-16 rounded-md object-cover mr-3 cursor-pointer hover:opacity-80 transition-opacity"
                            @click="openImageGallery(getImageArray(formData.environment_images), index)" />
                    </div>
                    <span v-else class="text-red-500">无图片</span>
                </el-form-item>

                <!-- 提交时间 -->
                <el-form-item label="提交时间：">
                    <span class="text-gray-700">{{ formData.create_time || '-' }}</span>
                </el-form-item>
            </el-form>

            <el-dialog v-model="dialogVisible" :title="'图片查看'" width="80%" class="rounded-lg overflow-hidden">
                <el-carousel v-if="imageList.length" v-model="currentImageIndex" arrow="always" class="h-96">
                    <el-carousel-item v-for="(image, index) in imageList" :key="index">
                        <el-image :src="image" fit="contain" class="w-full h-full" />
                    </el-carousel-item>
                </el-carousel>
            </el-dialog>
        </el-card>
    </div>
</template>

<script lang="ts" setup name="consumerDetail">
import { ref, reactive, shallowRef } from 'vue'
import type { FormInstance } from 'element-plus'
import { useRoute } from 'vue-router'

import { plantingAdjustMoney, getPlantingDetail, plantingEdit } from '@/api/Planting'
import { isEmpty } from '@/utils/util'
import AccountAdjust from '../components/account-adjust.vue'

const route = useRoute()
const formData = reactive({
    user_account: '',
    entity_name: '',
    credit_code: '',
    start_date: '',
    oper_name: '',
    status: '',
    no: '',
    comp_address: '',
    id_card: '',
    address: '',
    address_detail: '',
    field_name: '',
    location: '',
    variety_source: '',
    planting_area: '',
    planting_date: '',
    estimated_harvest_date: '',
    estimated_yield: '',
    total_harvest_times: '',
    total_yield: '',
    remaining_yield: '',
    circulation_info: '',
    contract_info: '',
    ownership_info: '',
    report_images: '',
    environment_images: '',
    create_time: ''
})

const adjustState = reactive({
    show: false,
    value: ''
})
const formRef = shallowRef<FormInstance>()
// 弹窗是否显示
const dialogVisible = ref(false)
// 当前图片列表
const imageList = ref<string[]>([])
// 当前图片索引
const currentImageIndex = ref(0)

// 从全局配置中获取基础 URL，这里先简单定义，实际使用时需要补充
const config = {
    baseUrl: ''
}

// 将图片数据转换为数组
const getImageArray = (images: string | string[]) => {
    return Array.isArray(images) ? images : images.split(',').map(img => img.trim())
}

// 获取完整的图片 URL
const getImageUrl = (image: string) => {
    return config.baseUrl + (typeof image === 'string' ? image.trim() : image)
}

// 打开图片浏览工具
const openImageGallery = (images: string[], index: number) => {
    imageList.value = images.map(getImageUrl)
    currentImageIndex.value = index
    dialogVisible.value = true
}

// 加载详情数据
const getDetails = async () => {
    try {
        const data = await getPlantingDetail({
            id: route.query.id
        })
        Object.keys(formData).forEach((key) => {
            //@ts-ignore
            formData[key] = data[key] || ''
        })
    } catch (error) {
        console.error('获取详情数据失败:', error)
    }
}

const handleEdit = async (value: string, field: string) => {
    if (isEmpty(value)) return
    try {
        await plantingEdit({
            id: route.query.id,
            field,
            value
        })
        getDetails()
    } catch (error) {
        console.error('编辑数据失败:', error)
    }
}

const handleAdjust = (value: string) => {
    adjustState.show = true
    adjustState.value = value
}

const handleConfirmAdjust = async (value: any) => {
    try {
        await plantingAdjustMoney({ user_id: route.query.id, ...value })
        adjustState.show = false
        getDetails()
    } catch (error) {
        console.error('调整金额失败:', error)
    }
}

getDetails()
</script>
